//
//  APIManager.m
//  Demo
//
//  Created by 拓客营 on 2022/3/24.
//

#import "APIManager.h"


#include <sys/types.h>
#include <sys/sysctl.h>


static APIManager * _instance;
static NSInteger TimeOutInterval = 15;
@implementation APIManager
+ (instancetype)manager {
    return [[self alloc] init];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

- (void)mainThreadSetNetworkActivityIndicatorVisible:(BOOL)set
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:set];
    });
}

#pragma mark - GET
- (void)Get:(NSString *)URLString parameters:(nullable id)parameters success:(successAPIBlock)success failure:(failureAPIBlock)failure {
  
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
      [responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",@"text/json",@"text/javascript",@"application/x-javascript",nil]];
    manager.responseSerializer = responseSerializer;
    manager.requestSerializer   = [AFHTTPRequestSerializer serializer];
//    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
    
    //添加请求头数据
    [self addRequestHeaderWithManager:manager];

    [self mainThreadSetNetworkActivityIndicatorVisible:YES];
    
    [manager GET:[NSString stringWithFormat:@"%@%@",BASEURL,URLString] parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self mainThreadSetNetworkActivityIndicatorVisible:NO];
        
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self mainThreadSetNetworkActivityIndicatorVisible:NO];
        if (failure) {
            failure(error);
        }
    }];
}

#pragma mark - POST
- (void)Post:(NSString *)URLString parameters:(nullable id)parameters success:(successAPIBlock)success failure:(failureAPIBlock)failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
      [responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",@"text/json",@"text/javascript",@"application/x-javascript",nil]];
    manager.responseSerializer = responseSerializer;
    manager.requestSerializer   = [AFHTTPRequestSerializer serializer];
    [manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
    
    
    //添加请求头数据
    [self addRequestHeaderWithManager:manager];

    [self mainThreadSetNetworkActivityIndicatorVisible:YES];
    
    [manager POST:[NSString stringWithFormat:@"%@%@",BASEURL,URLString] parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self mainThreadSetNetworkActivityIndicatorVisible:NO];
        
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self mainThreadSetNetworkActivityIndicatorVisible:NO];
        if (failure) {
            failure(error);
        }
    }];
}


#pragma mark - Image Upload
//- (void)uploadImages:(NSArray<UIImage *> *)images parameters:(nullable id)parameters success:(successAPIBlock)success failure:(failureAPIBlock)failure {
//
//    if (images.count == 0) {
//        success(@{@"code" : @1});
//        return;
//    }
//    AFHTTPSessionManager  *manager = [AFHTTPSessionManager manager];
//
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",@"text/json",@"text/javascript",nil];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.requestSerializer   = [AFHTTPRequestSerializer serializer];
//
//
//    // 添加请求头
//    [self addRequestHeaderAndSign:manager];
//
//    [self mainThreadSetNetworkActivityIndicatorVisible:YES];
//
//    [manager POST:[NSString stringWithFormat:@"%@%@",BASEURL,URL_ImgUpload] parameters:@{@"param":paramJson} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//
//        for (NSUInteger i = 0; i < images.count; i++) {
//
//            UIImage *oldImage = images[i];
//
//            UIImage *scaleImage = [oldImage compressWithMaxLength:0.5]; //压缩到0.5M
//            // 图片经过等比压缩后得到的二进制文件
//            NSData *imageData = UIImageJPEGRepresentation(scaleImage, 1.f);
//            // 默认图片的文件名, 若fileNames为nil就使用
//
//            if (!imageData) {
//
//                break;
//            }
//            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            formatter.dateFormat       = @"yyyyMMddHHmmss";
//            NSString *str              = [formatter stringFromDate:[NSDate date]];
//            NSString *imageFileName    = [NSString stringWithFormat:@"%@%zd.%@", str, i, @"png"];
//
//            [formData appendPartWithFormData:[@"1" toData] name:@"sourceType"];
//            [formData appendPartWithFileData:imageData name:@"file" fileName:imageFileName mimeType:[NSString stringWithFormat:@"image/%@", @"png"]];
//
//        }
//
//    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//        [self mainThreadSetNetworkActivityIndicatorVisible:NO];
//
//        success(responseObject);
//
//        [manager.session finishTasksAndInvalidate];
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//        [self mainThreadSetNetworkActivityIndicatorVisible:NO];
//
//        failure(error);
//        [manager.session finishTasksAndInvalidate];
//    }];
//
//
//}
//
//- (void)uploadSingleImages:(nullable UIImage *)image parameters:(nullable id)parameters success:(successAPIBlock)success failure:(failureAPIBlock)failure {
//
//    if (!image) {
//
//    }
//
//    AFHTTPSessionManager  *manager = [AFHTTPSessionManager manager];
//
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",@"text/json",@"text/javascript",nil];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.requestSerializer   = [AFHTTPRequestSerializer serializer];
//
//
//    // 添加请求头
//    [self addRequestHeaderAndSign:manager];
//
//    [self mainThreadSetNetworkActivityIndicatorVisible:YES];
//
//    [manager POST:[NSString stringWithFormat:@"%@%@",BASEURL,URL_ImgUpload] parameters:@{@"param":paramJson} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//
//        UIImage *scaleImage = [image compressWithMaxLength:0.5]; //压缩到0.5M
//        // 图片经过等比压缩后得到的二进制文件
//        NSData *imageData = UIImageJPEGRepresentation(scaleImage, 1.f);
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        formatter.dateFormat       = @"yyyyMMddHHmmss";
//        NSString *imageFileName    = [NSString stringWithFormat:@"%@.%@", [formatter stringFromDate:[NSDate date]], @"png"];
//
//        [formData appendPartWithFormData:[@"1" toData] name:@"sourceType"];
//        [formData appendPartWithFileData:imageData name:@"file" fileName:imageFileName mimeType:[NSString stringWithFormat:@"image/%@", @"png"]];
//
//
//    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//        [self mainThreadSetNetworkActivityIndicatorVisible:NO];
//
//        success(responseObject);
//
//        [manager.session finishTasksAndInvalidate];
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//        [self mainThreadSetNetworkActivityIndicatorVisible:NO];
//
//        failure(error);
//
//        [manager.session finishTasksAndInvalidate];
//    }];
//}

#pragma mark - uploadImage



#pragma mark - privacy method

-(void)addRequestHeaderWithManager:(AFHTTPSessionManager *)manager {
    //添加请求头数据
    [manager.requestSerializer setTimeoutInterval:TimeOutInterval];

//    [manager.requestSerializer setValue:self.token forHTTPHeaderField:@"Blade-Auth"];//设置到token
    
    [manager.requestSerializer setValue:self.token ? self.token : @"" forHTTPHeaderField:@"Blade-Auth"];
    
    NSString *authorStr = @"Basic c2FiZXI6c2FiZXJfc2VjcmV0";//Authorization
    [manager.requestSerializer setValue:authorStr forHTTPHeaderField:@"Authorization"];
    
    [manager.requestSerializer setValue:@"000000" forHTTPHeaderField:@"Tenant-Id"];
    
    [manager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"Client-Type"];
    
    
//    APISign *sign = [[APISign alloc]init];
//    [manager.requestSerializer setValue:sign.userAgent forHTTPHeaderField:@"user-device"];
////
//    [manager.requestSerializer setValue:[sign signWithURL:url json:jsonStr] forHTTPHeaderField:@"sign"];
//
//    [manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"registType"];

}

-(NSString *)configWithParameters:(nullable id)parameters {
    NSString *jsonStr = @"";
    if (parameters) {
        if ([parameters isKindOfClass:[NSDictionary class]]) {
            jsonStr = [NSString jsonStringCompactFormatForDictionary:parameters];
        }else if ([parameters isKindOfClass:[NSArray class]]) {
            jsonStr = [NSString jsonStringCompactFormatForNSArray:parameters];
        }
    }
    return jsonStr;
}


-(BOOL)resultConfigWithCode:(NSInteger)code{
    
    if (code == 1) {
        return YES;
    }else if (code == -1) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD hideHUDForView:[NSObject getCurrentViewController].view];
        [MBProgressHUD showMessage:@"请登录"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [YTClient.shared presentLoginControllerFrom:[NSObject getCurrentViewController] showClose:YES];
            [YTClient.shared logout];
//            [[NSObject getCurrentViewController].navigationController popToRootViewControllerAnimated:NO];
//            [NSObject getCurrentViewController].tabBarController.selectedIndex = 0;
        });
        return NO;
    }else if (code == -2) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD hideHUDForView:[NSObject getCurrentViewController].view];
        [MBProgressHUD showMessage:@"账号已被封禁"];
        return NO;
    }else if (code == -3) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD hideHUDForView:[NSObject getCurrentViewController].view];
//            [MBProgressHUD showMessage:@"版本更新"];
        return NO;
    }else if (code == -4) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD hideHUDForView:[NSObject getCurrentViewController].view];
        [MBProgressHUD showMessage:@"余额不足"];
        return NO;
    }
    return YES;
}



#pragma mark - 网络状态
//使用AFN框架来检测网络状态的改变
- (void)checkAFNReachability:(void (^)(AFNetworkReachabilityStatus status))block {
  //1.创建网络监听管理者
  AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
 
  //2.监听网络状态的改变
  /*
   AFNetworkReachabilityStatusUnknown     = 未知
   AFNetworkReachabilityStatusNotReachable   = 没有网络
   AFNetworkReachabilityStatusReachableViaWWAN = 3G
   AFNetworkReachabilityStatusReachableViaWiFi = WIFI
   */
  [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
      
      block(status);
      
    switch (status) {
      case AFNetworkReachabilityStatusUnknown:
        NSLog(@"未知");
        break;
      case AFNetworkReachabilityStatusNotReachable:
        NSLog(@"没有网络");
        break;
      case AFNetworkReachabilityStatusReachableViaWWAN:
        NSLog(@"3G");
        break;
      case AFNetworkReachabilityStatusReachableViaWiFi:
        NSLog(@"WIFI");
        break;
 
      default:
        break;
    }
  }];
 
  //3.开始监听
  [manager startMonitoring];
}
@end
